<template>
  <div class="app-container">
    <my-affix :offset="0" style="background: #fff;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <!-- <el-form-item label="商品id" prop="id">
        <el-input
          v-model="queryParams.goodsId"
          placeholder="请输入盲盒id"
          clearable
          
        />
      </el-form-item> -->
        <el-form-item label="产品名称" prop="title">
          <el-input v-model="queryParams.title" placeholder="请输入产品名称" clearable
                    
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select v-model="queryParams.status" clearable placeholder="请选择商品状态"
                     
          >
            <el-option v-for="item in [
              {
                value: '3',
                label: '全部',
              },
              {
                value: '2',
                label: '下架',
              },
              {
                value: '1',
                label: '上架',
              },
            ]" :key="item.value" :label="item.label" :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="库存" prop="stock">
        <el-input
          v-model="queryParams.stock"
          placeholder="请输入库存"
          clearable
          
        />
      </el-form-item>
      <el-form-item label="售卖数量" prop="saleNum">
        <el-input
          v-model="queryParams.saleNum"
          placeholder="请输入售卖数量"
          clearable
          
        />
      </el-form-item> -->
        <el-form-item label="产品价值" prop="price">
          <el-input v-model="queryParams.price" placeholder="请输入产品价值" clearable
                    
          />
        </el-form-item>
        <el-form-item label="回收价格" prop="money">
          <el-input v-model="queryParams.money" placeholder="请输入回收价格" clearable
                    
          />
        </el-form-item>
        <!-- <el-form-item label="第几套" prop="num">
        <el-input
          v-model="queryParams.num"
          placeholder="请输入第几套"
          clearable
          
        />
      </el-form-item> -->
        <el-form-item label="赏类型" prop="shangId">
          <el-select v-model="queryParams.shangId" clearable placeholder="请选择赏类型" @change="handleQuery">
            <el-option v-for="item in shang_option" :key="item.label" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable />
        </el-form-item>
        <!-- <el-form-item label="真实概率" prop="realPro">
        <el-input
          v-model="queryParams.realPro"
          placeholder="请输入真实概率"
          clearable
          
        />
      </el-form-item>
      <el-form-item label="显示概率" prop="lookPro">
        <el-input
          v-model="queryParams.lookPro"
          placeholder="请输入显示概率"
          clearable
          
        />
      </el-form-item>
      <el-form-item label="保底赏概率" prop="minPro">
        <el-input
          v-model="queryParams.minPro"
          placeholder="请输入保底赏概率"
          clearable
          
        />
      </el-form-item> -->

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-hasPermi="['system:list:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                     v-hasPermi="['system:list:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                     v-hasPermi="['system:list:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="9">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                     v-hasPermi="['system:list:export']"
          >导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-tag :type="realPro == 1 ? 'success' : 'danger'">真实概率:{{ realPro }}</el-tag>
        </el-col>
        <el-col :span="1.5">
          <el-tag :type="lookPro == 1 ? 'success' : 'danger'">显示概率:{{ lookPro }}</el-tag>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </my-affix>
    <el-table v-loading="loading" :data="listList" @selection-change="handleSelectionChange"
              @sort-change="dataListSortChangeHandle"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column sortable="custom" label="商品ID" align="center" prop="id"/>
      <el-table-column label="盲盒id" align="center" prop="goodsId"/>
      <el-table-column label="产品名称" align="center" prop="title"/>
      <el-table-column label="产品图片" align="center" prop="imgurl" width="120">
        <template slot-scope="scope">
          <el-image fit="cover" :src="scope.row.imgurl" style="width: 80px; height: 90px"/>
        </template>
      </el-table-column>
      <el-table-column label="背景框" align="center" prop="bgImgurl">
        <template slot-scope="scope">
          <el-image :src="scope.row.bgImgurl" style="width: 80px; height: 90px"/>
        </template>
      </el-table-column>
      <el-table-column label="赏分类" sortable="custom" align="center" prop="shangId">
        <template slot-scope="scope">
          {{ class_shang[scope.row.shangId] }}
        </template>
      </el-table-column>
      <el-table-column label="排序" sortable="custom" align="center" prop="sort"/>
      <!-- <el-table-column label="库存" sortable="custom" align="center" prop="stock" /> -->
      <!-- <el-table-column label="售卖数量" sortable="custom" align="center" prop="saleNum" >
        <template slot-scope="scope">
          {{ scope.row.stock - scope.row.saleNum }}/{{ scope.row.stock}}
        </template>
      </el-table-column> -->
      <el-table-column label="产品价值" sortable="custom" align="center" prop="price"/>
      <el-table-column label="回收价格" sortable="custom" align="center" prop="money"/>
      <el-table-column label="门槛" sortable="custom" align="center" prop="menkan"/>

      <el-table-column label="真实概率" sortable="custom" align="center" prop="realPro"/>

      <!-- <el-table-column label="保底赏概率" sortable="custom" align="center" prop="minPro" /> -->
      <el-table-column label="显示概率" sortable="custom" align="center" prop="lookPro"/>
      <el-table-column label="状态" align="center" prop="status" sortable="custom">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 1">上架</el-tag>
          <el-tag type="danger" v-if="scope.row.status == 2">下架</el-tag>
          <el-tag type="warning" v-if="scope.row.status == 3">删除</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column sortable="custom" label="1普通 2无限" align="center" prop="goodsType">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.goodsType == 1">普通</el-tag>
          <el-tag type="success" v-if="scope.row.goodsType == 2">无限</el-tag>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" label="0普通 1特殊" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.type == 0">普通</el-tag>
          <el-tag type="warning" v-if="scope.row.type == 1">特殊</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column sortable="custom" label="是否参与排行榜" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.ifCollect == 0">否</el-tag>
          <el-tag type="success" v-if="scope.row.ifCollect == 1">是</el-tag>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" label="是否参与熔铸" align="center" prop="ifAlchemy">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.ifAlchemy == 0">否</el-tag>
          <el-tag type="success" v-if="scope.row.ifAlchemy == 1">是</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="创建人" align="center" prop="creator"/>
      <el-table-column label="创建时间" align="center" prop="createDate" width="180" sortable="custom">
        <template slot-scope="scope">
          <span>{{
              parseTime(scope.row.createDate, '{y}-{m}-{d} {hh}:{mm}:{ss}')
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="createDate" width="180" sortable="custom">
        <template slot-scope="scope">
          <span>{{
              parseTime(scope.row.updateTime, '{y}-{m}-{d} {hh}:{mm}:{ss}')
            }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:list:edit']"
          >修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:list:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                :pageSizes="[20, 50, 100]" @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <!-- 快捷导入 -->
      <el-button v-if="form.id == null" style="margin-bottom: 20px" type="primary" @click="importExcel">快捷导入
      </el-button>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item  label="产品名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入产品名称"/>
        </el-form-item>
        <el-form-item  label="状态">
          <el-radio-group v-model.number="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item  label="赏图片" prop="imgurl">
          <image-upload :limit="1" v-model="form.imgurl"/>
        </el-form-item>

        <el-form-item  label="产品价值" prop="price">
          <el-tooltip class="item" effect="dark" content="产品价值为显示价值，不影响回收价值" placement="top-start">
            <el-input v-model="form.price" placeholder="请输入产品价值"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item  label="回收价格" prop="money">
          <el-input v-model="form.money" placeholder="请输入回收价格"/>
        </el-form-item>
        <el-form-item  label="赏ID" prop="shangId">
          <el-select v-model="form.shangId" clearable placeholder="请选择赏类型">
            <el-option v-for="item in shang_option" :key="item.label" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>


        <!-- <el-form-item label="${comment}" prop="addtime">
          <el-input v-model="form.addtime" placeholder="请输入${comment}" />
        </el-form-item> -->
        <el-form-item  label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序"/>
        </el-form-item>
        <!-- <el-form-item  label="阶段赏" prop="goodsInterval">
          <el-input v-model.number="form.goodsInterval" placeholder="请输入阶段赏次数"/>
        </el-form-item> -->
        <el-form-item  label="真实概率" prop="realPro">
          <el-tooltip class="item" effect="dark" content="奖品概率为奖池金额满足回收价的等级概率" placement="top-start">
            <el-input v-model="form.realPro" placeholder="请输入真实概率"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item  label="显示概率" prop="lookPro">
          <el-tooltip class="item" effect="dark" content="显示概率为玩家和审核看到的概率" placement="top-start">
            <el-input v-model="form.lookPro" placeholder="请输入显示概率"/>
          </el-tooltip>
        </el-form-item>
        <el-form-item  label="门槛" prop="menkan">
          <el-tooltip class="item" effect="dark"
                      content="设置奖品出奖门槛（一般设置为奖品本身金额，如果该等级奖品金额较大且概率过高，可以稍微设置高于奖品回收价值）"
                      placement="top-start"
          >
            <el-input v-model="form.menkan" placeholder="请输入门槛"/>
          </el-tooltip>
        </el-form-item>

        <!-- <el-form-item label="${comment}" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入${comment}" />
        </el-form-item>
        <el-form-item label="${comment}" prop="createDate">
          <el-date-picker
            clearable
            v-model="form.createDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择${comment}"
          >
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 快捷导入 -->
    <el-dialog title="快捷导入" :visible.sync="dialogVisible" width="80%" center>
      <importForm @func="update"/>
    </el-dialog>
  </div>
</template>

<script>
import {
  listList,
  getList,
  delList,
  addList,
  updateList,
  getType
} from '@/api/wxs/add_good.js'
import importForm from '@/components/importForm'

export default {
  name: 'AddBoxGoods',
  data() {
    return {
      lookPro: 0,
      realPro: 0,
      //是否打开快捷导入
      dialogVisible: false,
      //是否显示一键导入按钮
      showImport: false,
      shang_option: [],
      //赏类型对象
      class_shang: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      listList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        isAsc: '', // 排序，asc／desc
        orderByColumn: '', // 排序，字段
        box_id: null,
        pageNum: 1,
        pageSize: 100,
        goodsId: null,
        title: null,
        imgurl: null,
        status: null,
        stock: null,
        saleNum: null,
        price: null,
        money: null,
        num: null,
        shangId: null,
        addtime: null,
        sort: null,
        realPro: null,
        lookPro: null,
        minPro: null,
        goodsType: null,
        type: null,
        bgImgurl: null,
        creator: null,
        createDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {
            required: true,
            message: '请输入赏品名称',
            trigger: 'blur'
          }
        ],
        menkan: [
          {
            required: true,
            message: '请输入门槛',
            trigger: 'blur'
          }
        ],

        shangId: [
          { required: true, message: '请选择赏类型', trigger: 'change' }
        ],
        goodsId: [
          { required: true, message: '盲盒id不能为空', trigger: 'blur' }
        ],
        sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
        realPro: [
          { required: true, message: '真实概率不能为空', trigger: 'blur' }
          // { min: 0, max: 1, message: "真实概率不能大于1", trigger: "blur" },
        ],
        lookPro: [
          { required: true, message: '显示概率不能为空', trigger: 'blur' }
          // { min: 0, max: 1, message: "显示概率不能大于1", trigger: "blur" },
        ],
        money: [
          { required: true, message: '回收价值不能为空', trigger: 'blur' }
        ],
        goodsType: [
          { required: true, message: '1普通 2无限不能为空', trigger: 'change' }
        ],
        type: [
          { required: true, message: '0普通 1特殊不能为空', trigger: 'change' }
        ],
        price: [
          { required: true, message: '产品价值不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    importForm
  },
  created() {
    this.queryParams.goodsId = this.$route.params.boxId || null
    console.log(this.queryParams.goodsId)
    this.getType()
    this.getList()

    var _this = this
    document.onkeydown = function(e) {
      let key = window.event.keyCode
      if (key == 13) {
        _this.submitForm()
      }
    }
  },
  methods: {
    //接收一键导入表单数据
    update(value) {
      console.log(value)
      this.dialogVisible = false

      this.form = value
      this.form.id = null
      this.form.createDate = null
      this.form.goodsType = 2
      this.form.goodsId = this.queryParams.goodsId
    },

    //快捷导入

    importExcel() {
      this.dialogVisible = true
      console.log('弹窗')
    },

    //获取赏类型
    getType() {
      getType().then((res) => {
        console.log(res.rows)
        this.typeList = res.rows
        this.typeList.forEach((item) => {
          this.class_shang[item.id] = item.title
        })
        this.shang_option = this.typeList.map((item) => {
          return {
            value: item.id,
            label: item.title
          }
        })
        console.log(this.class_shang)
      })
    },

    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true

      listList(this.queryParams).then((response) => {
        this.listList = response.rows
        this.total = response.total
        this.loading = false
        this.countPro()
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      console.log('重置')
      this.form = {
        id: null,
        goodsId: this.queryParams.goodsId,
        title: null,
        imgurl: null,
        status: 2,
        stock: null,
        saleNum: null,
        price: null,
        money: null,
        num: null,
        shangId: null,
        addtime: null,
        sort: null,
        realPro: null,
        lookPro: null,
        minPro: null,
        goodsType: 2,
        type: null,
        bgImgurl: null,
        updateTime: null,
        creator: null,
        createDate: null,
        ifAlchemy: '0',
        goodsInterval: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1

      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.orderByColumn = ''
      this.queryParams.isAsc = ''
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.showImport = true
      this.reset()
      this.open = true
      this.title = '添加盒子商品'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.showImport = false
      this.reset()
      const id = row.id || this.ids
      getList(id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改盒子商品信息'
      })
    },
    //判断概率
    checkPro(val) {
      //根据id查询listList对应对象

      let list = this.listList.find((item) => item.id === this.form.id)
      //根据id查询listList对应对象的索引
      let index = this.listList.findIndex((item) => item.id === this.form.id)
      if (!val) {
        //修改查询出来的对象的ralePro和lookPro
        list.realPro = this.form.realPro
        list.lookPro = this.form.lookPro
        this.listList[index] = list
      }

      //将listList根shangId进行分组
      let group = this.listList.reduce((acc, cur) => {
        acc[cur.shangId] = acc[cur.shangId] || []
        acc[cur.shangId].push(cur)
        return acc
      }, {})
      console.log(group[9])

      //修改要修改shangId的商品的realPro和lookPro
      if (val) {
        if (group[val]) {
          group[val].forEach((item) => {
            item.realPro = this.form.realPro
            item.lookPro = this.form.lookPro
            updateList(item)
          })
        }
      } else {
        group[list.shangId].forEach((item) => {
          if (item.id !== this.form.id) {
            item.realPro = this.form.realPro
            item.lookPro = this.form.lookPro
            updateList(item)
          }
        })
      }
    },

    //统计总概率
    countPro() {
      //将listList根shangId进行分组
      // let group = this.listList.reduce((acc, cur) => {
      //   acc[cur.shangId] = acc[cur.shangId] || []
      //   acc[cur.shangId].push(cur)
      //   return acc
      // }, {})
      // console.log(group)

      //统计总概率
      this.lookPro = 0
      this.realPro = 0
      this.listList.forEach((item) => {
        this.lookPro = item.lookPro + this.lookPro
        this.realPro = item.realPro + this.realPro
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        this.form.updateTime = null

        this.form.goodsType = 2
        if (valid) {
          if (this.form.id != null) {
            // this.checkPro(false)
            updateList(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false 
              this.getList()
            })
          } else {
            // this.checkPro(this.form.shangId)
            this.form.creator = this.$store.getters.id
            this.form.sort = this.form.price
            addList(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除【请填写功能名称】编号为"' + ids + '"的数据项？')
        .then(function() {
          return delList(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/list/export',
        {
          ...this.queryParams
        },
        `list_${new Date().getTime()}.xlsx`
      )
    },
    //排序
    dataListSortChangeHandle(data) {
      if (!data.order || !data.prop) {
        this.queryParams.orderByColumn = ''
        this.queryParams.isAsc = ''
        return false
      }
      this.queryParams.isAsc = data.order.replace(/ending$/, '')
      this.queryParams.orderByColumn = data.prop
        .replace(/([A-Z])/g, '_$1')
        .toLowerCase()
      this.getList()
    }
  }
}
</script>
